package com.hk.commons;

import com.hk.commons.domain.service.ValidateService;
import com.hk.commons.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by Antinomy on 16/10/13.
 */

@FunctionalInterface
public interface ProcessAPI<T> {
    Logger logger = LoggerFactory.getLogger(ProcessAPI.class);

    default JsonResult process(HttpServletRequest request) {

        ValidateService validate = new ValidateService(request);

        return process(validate);
    }

    default JsonResult process(ValidateService validate) {
        JsonResult result = new JsonResult();
        try {
            result.resultCode = ResultCode.SUCC.getCode();
            result.msg = ResultCode.SUCC.getMsg();

            this.service(result, validate);
        } catch (ValidateException ex) {
            result = JsonResult.renderMsg(ResultCode.PARAM_ERROR, ex.getMessage());
        } catch (UserNotExistException ex) {
            result = JsonResult.renderMsg(ResultCode.USER_NOT_EXIST, ex.getMessage());
        } catch (EmptyResultDataAccessException ex) {
            result = JsonResult.renderMsg(ResultCode.NO_DATA, ex.getMessage());
        } catch (SystemException ex) {
            result = JsonResult.renderMsg(ResultCode.FAILED, ex.getMessage());
        } catch (SpecificException ex) {
            result = JsonResult.renderSpecificMsg(ResultCode.SPECIFIC_EXCEPTION, ex.getMessage());
        } catch (APIException ex) {
            result = JsonResult.renderMsg(ResultCode.FAILED, ex.getMessage());
            logger.error(ResultCode.FAILED.getMsg(), ex);
        } catch (Exception ex) {
            result = JsonResult.renderMsg(ResultCode.FAILED, ex.getMessage());
            logger.error(ResultCode.FAILED.getMsg(), ex);
            ex.printStackTrace();
        }

        return result;
    }

    void service(JsonResult<T> result, ValidateService validate) throws IOException;


}
